import binascii
import globalVar

def crc16(recData):
    b = 0xA001
    a = 0xFFFF
    length = len(recData) 
    for j in range(0,length- 2):
        a = a^recData[j]
        for i in range(8):
            last = a%2
            a = a>>1
            if last ==1: a = a^b
    aa = '0'*(6-len(hex(a)))+hex(a)[2:]
    ll,hh = int(aa[:2],16),int(aa[2:],16)
    a = recData[length - 2]
    b = recData[length - 1]
    if hh == recData[length - 2] and ll == recData[length - 1]:
        return True
    else:
        return False

def onProcData(recData):
    if crc16(recData):
        writeData = modbusFnSort(recData)
        return writeData
    else:
        return None

# 实时数据01 03 00 78 00 0F 85 D7

tupleModbusFn = ('onProcCoilSts', 'onProcInpSts', 'onProcHoldingReg', 'onProcInpReg' ,'onProcForceSglCoil', 'onProcPresetSglReg')
def modbusFnSort(recData):
    dictModbusFnfunc = {'onProcHoldingReg': onProcHoldingReg, 'onProcPresetSglReg': onProcPresetSglReg}
    offset = recData[1] - 1
    funcName = tupleModbusFn[offset]
    return dictModbusFnfunc[funcName](recData)

def onProcHoldingReg(recData):
    # 暂时先固定时，后续改为随机产生数值
    if recData[3] == 0x78 and recData[5] == 0x0F:  # 氨表实时数据申请
        writeData = bytes([0x01, 0x03, 0x1E, 0x00, 0xA5, 0x00, 0xA5, 
        0x00, 0xA5, 0x00, 0x55,0x00, 0xA5, 0x00, 0xA5, 0x00, 0x00, 
        0x00, 0x00, 0x99, 0x9A, 0x3F, 0x99, 0x66, 0x66, 0x3F, 0xA6, 0x33, 0x33, 0x3F, 0xB3, 0x00, 0x00, 0x45, 0x4A,])   
        return writeData
    else:
        return None

def onProcPresetSglReg(recData):
    if recData[3] == 0x78 and recData[5] == 0x0F:
        writeData = [0x01, 0x03, 0x1E, 0x00, 0xA5, 0x00, 0xA5, 
        0x00, 0xA5, 0x00, 0x55,0x00, 0xA5, 0x00, 0xA5, 0x00, 0x00, 
        0x00, 0x00, 0x99, 0x9A, 0x3F, 0x99, 0x66, 0x66, 0x3F, 0xA6, 0x33, 0x33, 0x3F, 0xB3, 0x00, 0x00, 0x45, 0x4A,]